package Servlet;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

public class Download extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String downloadFileName="2.jpg";
        //获取servlet上下文信息
        ServletContext servletContext = getServletContext();
        //获取要下载的文件类型
        String mimeType = servletContext.getMimeType("/file/"+downloadFileName);
        System.out.println("下载的文件类型"+mimeType);
        //设置响应的文件类型
        response.setContentType(mimeType);
        //设置选择下载的方式
        response.setHeader("Content-Disposition","attachment;filename"+ URLEncoder.encode("广哥的图","UTF-8"));//URL编码
        //将路径下的资源当作以一个输入流输入到服务器中
        InputStream resourceAsStream = servletContext.getResourceAsStream("/file/"+downloadFileName);
        //从服务器种输出到一张纸上
        OutputStream outputStream = response.getOutputStream();
        //将输入流直接复制给输出流
        IOUtils.copy(resourceAsStream,outputStream);


    }
}
